﻿using System;
using System.Windows.Data;
using System.Windows;
using System.Windows.Input;


namespace BadHabit.WPFTools {

    /// <summary>
    /// Thanks to Mike.
    /// http://mikescodeblog.blogspot.com/2007/12/drag-and-drop-in-wpf.html
    /// </summary>
    public class DragDropHandler {
        private FrameworkElement dragElement = null;
        private bool dragging = false;
        
        private Point dragStart;
        private DataObject dataObject = null;

        public DragDropHandler(FrameworkElement dragElement, DataObject dataObject) {
            this.dragElement = dragElement;
            this.dataObject = dataObject;

            dragElement.PreviewMouseDown += new MouseButtonEventHandler(dragElement_MouseLeftButtonDown);            
            dragElement.MouseMove += new MouseEventHandler(dragElement_MouseMove);
            dragElement.PreviewMouseUp += new MouseButtonEventHandler(dragElement_PreviewMouseUp);
        }

        void dragElement_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
            dragging = false;
            dragElement.ReleaseMouseCapture();
        }


        void dragElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
            if (e.Source is ComboBox)
                return;
            if (!dragging) {
                dragging = true;                
                dragStart = e.GetPosition(dragElement);
            }
        }

        bool indrag = false;

        void dragElement_MouseMove(object sender, MouseEventArgs e) {
            if (dragging && e.LeftButton == MouseButtonState.Pressed && !indrag) {

                Point currentPos = e.GetPosition(dragElement);



                if ((Math.Abs(currentPos.X - dragStart.X) > 5) || (Math.Abs(currentPos.Y - dragStart.Y) > 5)) {

                    dragElement.CaptureMouse();
                    indrag = true;

                    

                    //Console.WriteLine("start drag"); 
                    DragDropEffects de = DragDrop.DoDragDrop(dragElement, dataObject, DragDropEffects.Move);
                    //Console.WriteLine("end drag");
                    indrag = false;
                    dragging = false;
                    dragElement.ReleaseMouseCapture();
                    


                }
            }
        }

        
    }
}
